import axios, { AxiosRequestConfig } from 'axios'
// import Config from "../../../../config";
import { Toast } from 'vant'
import { VanToast } from 'vant/types/toast'
import { getToken } from './token'

// let preUrl = process.env.NODE_ENV === "development" ? "/api" : "";
export const preUrl: string =
  process.env.NODE_ENV === 'development'
    ? '/api'
    : process.env.VUE_APP_API_BASE_HOST || ''

const instance = axios.create({
  timeout: 10000 // 设置10s为超时
})

let LoadingToast: VanToast

// 设置请求拦截器
instance.interceptors.request.use(
  config => {
    const { loading } = config
    if (loading) {
      LoadingToast = Toast.loading({
        // message: "加载中...",
        forbidClick: true,
        loadingType: 'spinner'
      })
    }
    return config
  },
  () => {
    LoadingToast && LoadingToast.clear()
    const msg = '当前网络不佳，请稍后再试'
    return Promise.reject({
      msg
    })
  }
)

// 设置响应拦截器
instance.interceptors.response.use(
  res => {
    const message = '当前网络不佳，请稍后再试'
    LoadingToast && LoadingToast.clear()
    const { success, code, msg, data } = res.data
    if (!success) {
      // if (code === "1001010" || code === "1002001") {
      // let { origin, pathname, hash } = location;
      // let href = `${origin}${pathname}`;
      // let hashQuery = hash.split("#")[1];
      // location.href = `${href}/#/login?redirect=${encodeURIComponent(
      //   hashQuery
      // )}`;
      //   return Promise.reject({
      //     code,
      //     message: "登录信息失效,请重新登录"
      //   });
      // }
      return Promise.reject({
        code,
        data,
        msg: msg || message
      })
    }
    // console.log(res);
    const resConfig = res.config
    resConfig.toast && Toast.success(msg)
    if (resConfig.whole) {
      return res.data
    }
    return data
  },
  err => {
    let msg = '当前网络不佳，请稍后再试'
    LoadingToast && LoadingToast.clear()
    // neterror
    if (!err.response) {
      msg = '无法连接到服务器，请稍后再试'
      // Toast(message)
      // return Promise.reject({
      //   message
      // });
    }
    if (err.response.status == 403) {
      const { origin, pathname } = window.location
      const href = `${origin}${pathname}`
      // let hashQuery = hash.split("#")[1];
      location.href = `${href}#/login`
      msg = '登录信息失效,请重新登录'
      // Toast(message)
      // return Promise.reject({
      //   message
      // });
    }
    if (err.response.status == 500) {
      console.log(err.response)
      msg = err.response.statusText
    }
    Toast(msg)
    return Promise.reject({
      msg
    })
  }
)
/**
 * 头部信息设置token方法
 */
instance.setToken = function(token) {
  const effecToken = token || getToken()
  this.defaults.headers.common['Authorization'] = effecToken || ''
}
// 页面加载先设置一次，如果没有则为空字符串
// 解决--非登录途径进入页面后，不加载本地缓存的token，头信息就会为空
instance.setToken('')

/**
 * 针对网关接口统一封装一个api
 * @param {string} url 接口地址
 * @param {object} param 接口参数
 * @param {boolean} loading 是否全局toast
 * @returns {promise} 返回promise
 */
export function api(url: string, param = {}, cfg: AxiosRequestConfig = {}) {
  const { loading, toast, whole } = cfg
  // return apiInstance.post(url, param, loading, setToken);
  return instance({
    loading,
    toast,
    whole,
    url: preUrl + url,
    method: 'post',
    data: {
      ...param
    }
  })
}
/**
 * 针对网关接口统一封装一个api
 * @param {string} url 接口地址
 * @param {object} param 接口参数
 * @param {boolean} loading 是否全局toast
 * @returns {promise} 返回promise
 */
export function get(url: string, param = {}, cfg: AxiosRequestConfig = {}) {
  const { loading, toast, whole } = cfg
  // return apiInstance.post(url, param, loading, setToken);
  return instance({
    loading,
    toast,
    whole,
    url: preUrl + url,
    method: 'get',
    params: {
      ...param
    }
  })
}

export default instance
